#!/bin/sh /etc/rc.common
#
# Copyright (C) 2014-2018 OpenWrt-dist
# Copyright (C) 2014-2018 Jian Chang <aa65535@live.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#

START=90

USE_PROCD=1

append_bool() {
	local section="$1"
	local option="$2"
	local value="$3"
	local default="$4"
	local _loctmp
	config_get_bool _loctmp "$section" "$option" "$default"
	[ "$_loctmp" = 1 ] || return 0
	procd_append_param command "$value"
}

append_parm() {
	local section="$1"
	local option="$2"
	local switch="$3"
	local default="$4"
	local _loctmp
	config_get _loctmp "$section" "$option"
	[ -n "$_loctmp" -o -n "$default" ] || return 0
	procd_append_param command "$switch" "${_loctmp:-$default}"
}

start_instance() {
	local enable
	config_get_bool enable $1 enable
	[ "$enable" = 1 ] || return 0

	procd_open_instance
	procd_set_param respawn
	procd_set_param stderr 1
	procd_set_param command /usr/bin/chinadns -m
	append_parm $1 addr "-b"
	append_parm $1 port "-p"
	append_parm $1 server "-s"
	append_parm $1 chnroute "-c"
	append_bool $1 bidirectional "-d"
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "chinadns"
}

start_service() {
	config_load chinadns
	config_foreach start_instance chinadns
}
